package com.cityView.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.cityView.entity.WeChatProperties;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class WeChatService {
    @Autowired
    private WeChatProperties weChatProperties;

    public String getCode2Session(String code) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            String url = "https://api.weixin.qq.com/sns/jscode2session?" +
                    "appid=" + weChatProperties.getAppId() +
                    "&secret=" + weChatProperties.getAppSecret() +
                    "&js_code=" + code +
                    "&grant_type=authorization_code";
            HttpGet httpGet = new HttpGet(url);
            org.apache.http.HttpResponse response = httpClient.execute(httpGet);
            String result = EntityUtils.toString(response.getEntity(), "UTF-8");
            // 这里可以根据返回的JSON数据进一步处理，比如解析openid和session_key
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(result);
            String openId = jsonNode.get("openid").asText();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("openid",openId);
            System.out.println(jsonObject);
            return jsonObject.toJSONString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
